import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import router from 'umi/router';
import { Row, Col, Card, Icon, Button, Dropdown, Popconfirm, message, Divider, Form, Select, Input} from "antd";
import MaintainPerson from '../../Form/MaintainPerson';
import StandardTable from '../../../components/StandardTable';
import Authorized from '../../../utils/Authorized';
import styles from '../../Pbulic.less';

const FormItem = Form.Item;
const { Option } = Select;


const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ plan, global,loading }) => ({
  dictionaries:global.dictionaries,
  selectSource:global.selectSource,
  resdata: plan.resdata,
  loading: plan.loading,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class ListTable extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      pageSize: 10,
      selectedRows: [],
      formValues: {},
    };
  }



  componentDidMount() {
    const { pageSize } = this.state;
    const { pagesquery, dispatch} = this.props;
    // 维保单位列表
    dispatch({
      type: 'global/fetch_select_maintencompany',
    });
    // // 养护人
    // dispatch({
    //   type: 'global/fetch_select_maintenman',
    // });

    // 列表
    this.getDataList(pagesquery,pageSize,1);
  }

  // componentWillReceiveProps(nextProps) {
  //   // 外层发起刷新数据请求
  //   if (nextProps.isReloadList === true && this.props.isReloadList === false) {
  //     const { pageSize } = this.state;
  //     this.getDataList({},pageSize,1);
  //     this.props.sotpReloadList();
  //   }
  // }


  getDataList(params,pageSize,currentPage) {
    const { dispatch } = this.props;
    dispatch({
      type: 'plan/fetch_plan_list',
      payload: {
        pageSize,
        currentPage,
        // ...pagesquery,
        ...params,
        maintenanceInfo:undefined,
      },
    });
  }

  // 维保单位关联人搜索事件-------------------------------------
  handleSearchMaintain = ( value ) =>{
    const { dispatch } = this.props;
    const maintenanceId=value.maintenanceId;
    const userId=value.userId;
    const loadData=value.loadData;

    if(userId===0){
      // 清空子节点操作
      dispatch({
        type: 'global/fetch_clear_maintenman',
      })
    }

    if(loadData && maintenanceId!==0){
      dispatch({
        type: 'global/fetch_select_maintenman',
        payload: {
          deptId:maintenanceId,
        },
      })
    }
  }



  // 分页、排序、筛选变化时触发
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      // currentPage: pagination.current,
      // pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.setState({
      currentPage:pagination.current
    },()=>{
      this.getDataList(params,pageSize,pagination.current);
    })

  };

  // 重置表单
  handleFormReset = () => {
    const { form } = this.props;
    const {pageSize,currentPage} = this.state;
    //form.resetFields();
    form.setFieldsValue({
      planCode:undefined,
      planName:undefined,
      planType:undefined,
      maintenanceInfo:{ maintenanceId:0, userId:0 },
    });
    this.setState({
      formValues: {},
    });
    this.getDataList({},pageSize,1);
  };


  // 表格复选框选中
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows.map(item => item.planId),
    });
  };

  // 表单搜索
  handleSearchSubmit = e => {
    e.preventDefault();

    const { form } = this.props;
    const { pageSize } = this.state;




    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if(fieldsValue.maintenanceInfo && fieldsValue.maintenanceInfo.maintenanceId!==0){
        fieldsValue.maintenanceId = fieldsValue.maintenanceInfo.maintenanceId;
      }
      if(fieldsValue.maintenanceInfo && fieldsValue.maintenanceInfo.userId!==0){
        fieldsValue.maintainManId = fieldsValue.maintenanceInfo.userId;
      }

      this.setState({
        formValues: fieldsValue,
      });

      this.getDataList(fieldsValue,pageSize,1);
    });
  };



  // 批量删除
  handleActionList = (type,id) => {
    const { dispatch } = this.props;
    const { selectedRows,formValues, pageSize, currentPage } = this.state;
    if(!id && !selectedRows) return;
    const planIds= id ? [id] : selectedRows;

    switch (type) {
      case '1':
        dispatch({
          type: 'plan/action_plan_stop',
          payload: {
            planIds
          },
        }).then(()=>{
          this.setState({
            selectedRows: [],
          });
        }).then(()=>{
          message.success("所选计划已中止")
        }).then(()=>{
          this.getDataList(formValues,pageSize,currentPage);
        });
        break;
      case '2':
        dispatch({
          type: 'plan/action_plan_del',
          payload: {
            planIds
          },
        }).then(()=>{
          this.setState({
            selectedRows: [],
          });
        }).then(()=>{
          message.success("所选计划已删除")
        }).then(()=>{
          this.getDataList(formValues,pageSize,currentPage);
        });

      default:

        break;
    }
  };


  // 链接跳转-------------------
  handleLink = (action,detailInfoId) =>{
    const { dispatch } = this.props;
    const { formValues, currentPage} = this.state;
    let linkpath;
    switch (action) {
      case 'add':
        linkpath = `/maintain/plan/detail/add`;
        break;
      case 'edit':
        linkpath = `/maintain/plan/detail/edit/${detailInfoId}`;
        break;
      case 'info':
        linkpath = `/maintain/plan/detail/info/${detailInfoId}`;
        break;
      default:
        break;
    }
    router.push({ pathname:`${linkpath}`,  query: { ...formValues, currentPage} });
  }


  // 搜索内容
  renderSearchForm() {
    const { form, dictionaries, selectSource, pagesquery } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearchSubmit} >
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="计划编号">
              {getFieldDecorator('planCode',{
                initialValue: pagesquery && pagesquery.planCode ? pagesquery.planCode : undefined,
              })(<Input placeholder="请输入计划编号" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="计划名称">
              {getFieldDecorator('planName',{
                initialValue: pagesquery && pagesquery.planName ? pagesquery.planName : undefined,
              })(<Input placeholder="请输入计划名称" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
              <FormItem label="计划类型">
                {getFieldDecorator('planType',{
                  initialValue: pagesquery && pagesquery.planType ? pagesquery.planType : undefined,
                })(
                  <Select allowClear={true} placeholder="请选择计划类型"   style={{ width: '100%' }}>
                    {dictionaries.planExecuteTime && dictionaries.planExecuteTime.map(item => (
                      <Option key={item.value} value={item.value}>{item.label}</Option>
                    ))}
                  </Select>
                )}
              </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={16} sm={24}>
            <FormItem  label="维保单位">
              {getFieldDecorator("maintenanceInfo", {
                initialValue: pagesquery && pagesquery.maintenanceInfo ? pagesquery.maintenanceInfo : { maintenanceId:0, userId:0 },
              })(
                <MaintainPerson
                  placeholder={"请选择养护人"}
                  maintainData={selectSource.maintenance}
                  personnelData={selectSource.maintenman}
                  onChange={this.handleSearchMaintain}
                />
              )}
            </FormItem>
          </Col>


          <Col md={8} sm={24}>
            <div style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </div>
          </Col>

        </Row>
      </Form>
    );
  }


  render() {

    const { resdata, loading, dictionaries } = this.props;
    const { selectedRows } = this.state;
    const planExecuteTime = dictionaries.planExecuteTime && dictionaries.planExecuteTime.length>1
      ? dictionaries.planExecuteTime.map(item=>item.label)
      :[];
    const planStatus = dictionaries.planStatus && dictionaries.planStatus.length>1
      ? dictionaries.planStatus.map(item=>item.label)
      :[];

    const columns = [
      {
        title: '计划编号',
        dataIndex: 'planCode',
        render: text => text ? `${text}` : '--',
      },
      {
        title: '计划名称',
        dataIndex: 'planName',
      },
      {
        title: '计划类型',
        dataIndex: 'planType',
        render: (text)=> (
          <span>{planExecuteTime[parseInt(text)-1]}</span>
        ),
      },
      {
        title: '执行周期',
        dataIndex: 'executeTime',
        render: text => text ? `每 ${text} 日` : '--',
      },
      {
        title: '维保单位',
        dataIndex: 'maintenanceName',
        render: text => text ? `${text}` : '--',
      },
      {
        title: '养护人',
        dataIndex: 'maintainManName',
        render: text => text ? `${text}` : '--',
      },
      {
        title: '状态',
        dataIndex: 'planStatusName',
        // render: (text)=> (
        //   <span>{planStatus[parseInt(text)-1]}</span>
        // ),
      },
      {
        title: '操作',
        width: 250,
        fixed:'right',
        render: (text, row, index) => (
          <Fragment>
            <Authorized authority={'10113'} >
              <a onClick={() => this.handleLink('info',row.planId)}>详情</a>
              <Divider type="vertical" />
            </Authorized>
            <Authorized authority={'10114'} >
              <a onClick={() => this.handleLink('edit',row.planId)}>修改</a>
              <Divider type="vertical" />
            </Authorized>
            <Authorized authority={'10115'} >
              {row.status!=="03" && <Popconfirm title="是否确定要中止计划?" onConfirm={() => this.handleActionList("1",row.planId)}  okText="是" cancelText="否">
                <a >中止</a>
              </Popconfirm>}
              {row.status=="03" && <span style={{color:'#ccc'}}>中止</span>}
              <Divider type="vertical" />
            </Authorized>
            <Authorized authority={'10116'} >
              <Popconfirm title="是否确定要删除?" onConfirm={() => this.handleActionList("2",row.planId)}  okText="是" cancelText="否">
                <a >删除</a>
              </Popconfirm>
            </Authorized>
          </Fragment>
        ),
      },
    ];




    return (
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderSearchForm()}</div>
          <div className={styles.tableListOperator}>
            <Authorized authority={'10112'} >
              <Button icon="plus" type="primary"  onClick={() => this.handleLink('add',null)}>
                新增计划
              </Button>
            </Authorized>

            <Authorized authority={'10117'} >
            <Popconfirm title="是否确定要批量删除?" onConfirm={() => this.handleActionList("2")}  okText="是" cancelText="否">
              <Button icon="minus" type="default" disabled={selectedRows.length > 0 ? false : true}>
                批量删除
              </Button>
            </Popconfirm>
            </Authorized>
            {/*
               <Button type="default" onClick={() => this.handleActionList("2")}>
                导出
              </Button>
            */}

          </div>
          <StandardTable
            selectedRows={selectedRows}
            rowKey="planId"
            scroll={{ x: 1500 }}
            loading={loading.reslist}
            data={resdata}
            columns={columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </div>
      </Card>

    );
  }
}
